script_name=$0
pyexec='python3'
file_server='tornado_run_server.py'
pid_file='run.pid'
log_file='./log/run.log'

function usage () {
    echo "usage : "
    echo "$(basename ${script_name}) { start | stop | restart } "
    echo ""
}

if [[ $# != 1 || ( "$1" != "start" && "$1" != "stop" && "$1" != "restart" ) ]]; then
    usage;
    exit 1;
fi

function start_func() {
    echo 'startting...'
    # nohup $pyexec $file_server 2>/dev/null 1>&2 &
    source /home/gsw945/vev3gsw945/bin/activate
    nohup $pyexec $file_server $@ > $log_file &
    echo $! > $pid_file # '$!' return the pip of the current started process
    echo 'running...'
}

function stop_func() {
    echo 'stopping...'
    #refer: http://www.cnblogs.com/ITtangtang/p/3950490.html
    #kill -9 $(ps -ef | grep ${script_name})
    # tmp1=$(ps -eo pid,cmd | awk '{print $1, $pyexec, $3}' | grep $file_server)
    # len=${tmp1} | wc -L 2>/dev/null 1>&2
    # len=${tmp1} | wc -L
    # min_len=6
    # if [[ $len -lt $min_len ]];then
    # OLD_IFS="$IFS"
    # IFS=" "
    # arr=($tmp1)
    # IFS="$OLD_IFS"
    # echo 'stopping with pid='${arr[1]}
    # kill -9 ${arr[1]} 2>/dev/null 1>&2

    pid=`cat $pid_file`
    # ps -ef | grep "process name" | wc -l # return the runnig process count with contains the process name, 0 or other integer
    exist=`ps --no-heading $pid | wc -l` # return the running process count with the pid, only 0(not fount) or 1(found)
    exist=`ps --no-heading $pid | wc -l`
    if [[ $exist -eq 1 ]];then
    kill $pid
    # $?符号显示上一条命令的返回值，如果为0则代表执行成功，其他表示失败
    if [[ $? -eq 0 ]];then
            sleep 3s
    else
        :
    fi
    echo 'stopped.'
    else
    echo 'not running.'
    fi
    # echo ${script_name}
}

function restart_func() {
    stop_func;
    sleep 5
    start_func;
}

case $1 in
    "start" )
        start_func;
        ;;
    "stop" )
        stop_func;
        ;;
    "restart" )
        restart_func;
esac

echo ""
